package com.yswl.yeeduo.ui.task;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.SnsPostListener;
import com.umeng.socialize.controller.listener.SocializeListeners.SocializeClientListener;
import com.umeng.socialize.controller.listener.SocializeListeners.UMAuthListener;
import com.umeng.socialize.controller.listener.SocializeListeners.UMDataListener;
import com.umeng.socialize.exception.SocializeException;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.umeng.socialize.weixin.media.CircleShareContent;
import com.umeng.socialize.weixin.media.WeiXinShareContent;
import com.yswl.yeeduo.http.KAsyncTask.TaskDelegate;
import com.yswl.yeeduo.tool.KLog;
import com.yswl.yeeduo.tool.KStringTool;
import com.yswl.yeeduo.ui.bean.ActiviteDetailBean;
import com.yswl.yeeduo.ui.bean.WXUserInfo;
import com.yswl.yeeduo.ui.fragment.LuckyMoneyActivityFragment;
import com.yswl.yeeduo.ui.fragment.MyMoneyFragment;
import com.yswl.yeeduo.ui.tool.ServiceAuthManager;
import com.yswl.yeeduo.ui.tool.ToastUtil;
import com.yswl.yeeduo.ui.tool.UserManger;
import com.yswl.yeeduo.ui.utils.FileSaveUtil;
import com.yswl.yeeduo.view.dialog.LoadingProgressDialog;

/**
 * 微信授权 用友盟
 * 
 * @author Administrator
 */
public class WXAuthByUm {
	public static final String wxAPPID = "wxfc6dbf530c4c5829";// 申请的合法appId
	public static final String wxAPPSECRET = "f6ef48d7337204af921444688afb7e49";// 微信开放平台提供

	protected static final String TAG = "WxLogin";

	private Context mContext;

	public WXAuthByUm(Context context) {
		mContext = context;
	}

	/**
	 * 绑定微信 本方法是友盟第三方微信授权 + 绑定微信接口
	 */
	public void WxAuthByUM() {
		final UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.login");
		/** 添加微信平台 **/
		UMWXHandler wxHandler = new UMWXHandler(mContext, WXAuthByUm.wxAPPID, WXAuthByUm.wxAPPSECRET);
		wxHandler.addToSocialSDK();
		startProgressDialog();
		if (!wxHandler.isClientInstalled()) {
			ToastUtil.showShortMsg("亲，没安装微信哦~");
			stopProgressDialog();
			return;
		}
		mController.doOauthVerify(mContext, SHARE_MEDIA.WEIXIN, new UMAuthListener() {
			@Override
			public void onStart(SHARE_MEDIA platform) {
			}

			@Override
			public void onError(SocializeException e, SHARE_MEDIA platform) {
				ToastUtil.showShortMsg("授权失败");
				stopProgressDialog();
			}

			@Override
			public void onComplete(Bundle value, SHARE_MEDIA platform) {
				/* access_token 接口调用凭证************************** */
				/* expires_in access_token接口调用凭证超时时间，单位（秒） */
				/* refresh_token 用户刷新access_token */
				/* openid 授权用户唯一标识 */
				/* scope 用户授权的作用域，使用逗号（,）分隔 */
				/* unionid 只有在用户将公众号绑定到微信开放平台帐号后，才会出现该字段。 */
				stopProgressDialog();
				String access_token = value.getString("access_token");
				final String unionid = value.getString("unionid");
				final String openid = value.getString("openid");
				KLog.e(TAG, "-------------友盟微信登录授权-------->access_token=" + access_token + " ,unionid=" + unionid + " ,openid=" + openid);
				UserManger.getInstance().recordWxParameter(mContext, access_token, unionid, openid);
				// 获取相关授权信息
				mController.getPlatformInfo(mContext, SHARE_MEDIA.WEIXIN, new UMDataListener() {
					@Override
					public void onStart() {
						if (KLog.isShow) {
							Toast.makeText(mContext, "获取平台数据开始...", Toast.LENGTH_SHORT).show();
						}
					}

					@SuppressWarnings("unchecked")
					@Override
					public void onComplete(int status, Map<String, Object> info) {
						if (status == 200 && info != null) {
							// TODO 服务器登录
							WXUserInfo.saveWxUserInfo(info);// 保存信息 本地数据库
							// new LoginTask(mContext, 1000,
							// delegate).execute();

							String headimgurl = (String) info.get("headimgurl");
							String headNetUrl = "http://s.lifedoo.cn:8088/M00/00/03/CqgtmFYcoBWABGLzAAAKfwn89nU078.png";
							headimgurl = KStringTool.isEmpty(headimgurl) ? headNetUrl : headimgurl;
							String province = (String) info.get("province");
							int sex = (Integer) info.get("sex");
							String nickname = (String) info.get("nickname");

							Map<String, String> params = new TreeMap<String, String>();
							String userId = ServiceAuthManager.getUserId(mContext);
							if (KStringTool.isEmpty(userId)) {
								userId = "-1";
							}
							params.put("userId", userId);
							params.put("api_key", ServiceAuthManager.getToken(mContext));
							params.put("openid", openid);
							params.put("unionid", unionid);
							params.put("logo", headNetUrl);
							params.put("nickname", nickname);
							params.put("source", "2");
							params.put("sex", sex + "");

							// FileSaveUtil.saveCrashLogToFile(params);
							if (check(params) == true) {
								new BindWxTask(mContext, BindWxTask.TASKID, new TaskDelegate() {
									@Override
									public void faild_TaskDelegate(int taskId, Object object) {
										if (KLog.isShow) {
											ToastUtil.showShortMsg("绑定微信失败");
										}
									}

									@Override
									public void success_TaskDelegate(int taskId, Object object) {
										MyMoneyFragment.sendBroadcast(mContext);
										if (KLog.isShow) {
											ToastUtil.showShortMsg("绑定微信成功");
										}

									}
								}).execute(params);
							}
						} else {
							KLog.e(TAG, "------微信获取用户信息发生错误----->" + status);
						}
					}

				});
			}

			@Override
			public void onCancel(SHARE_MEDIA platform) {
				stopProgressDialog();
				// Toast.makeText(mContext, "授权取消", Toast.LENGTH_SHORT).show();
			}
		});
	}

	/**
	 * 退出微信登录
	 */
	public void exitWxLogin() {
		final UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.login");
		/** 添加微信平台 **/
		UMWXHandler wxHandler = new UMWXHandler(mContext, WXAuthByUm.wxAPPID, WXAuthByUm.wxAPPSECRET);
		wxHandler.addToSocialSDK();
		mController.deleteOauth(mContext, SHARE_MEDIA.SINA, new SocializeClientListener() {
			@Override
			public void onStart() {
			}

			@Override
			public void onComplete(int status, SocializeEntity entity) {
				if (status == 200) {
					Toast.makeText(mContext, "注销成功", Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(mContext, "注销失败", Toast.LENGTH_SHORT).show();
				}
			}
		});
	}

	private boolean check(Map<String, String> mLogInfo) {
		for (Map.Entry<String, String> entry : mLogInfo.entrySet()) {
			String value = entry.getValue();
			if (KStringTool.isEmpty(value)) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 友盟默认弹出面板分享
	 */
	@Deprecated
	public void WxShareByUmDefault(final ActiviteDetailBean redBean) {
		if (mContext == null || redBean == null) {
			return;
		}

		// 添加微信平台
		UMWXHandler wxHandler = new UMWXHandler(mContext, WXAuthByUm.wxAPPID, WXAuthByUm.wxAPPSECRET);
		wxHandler.addToSocialSDK();
		// 添加微信朋友圈
		UMWXHandler wxCircleHandler = new UMWXHandler(mContext, WXAuthByUm.wxAPPID, WXAuthByUm.wxAPPSECRET);
		wxCircleHandler.setToCircle(true);
		wxCircleHandler.addToSocialSDK();
		wxCircleHandler.showCompressToast(false);// 去掉微信自身的toast

		UMSocialService mController_share = UMServiceFactory.getUMSocialService("com.umeng.share");// 友盟分享
		mController_share.getConfig().removePlatform(SHARE_MEDIA.SINA, SHARE_MEDIA.QZONE, SHARE_MEDIA.QQ, SHARE_MEDIA.TENCENT);
		mController_share.getConfig().setPlatformOrder(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE);
		mController_share.getConfig().closeToast();// 关掉友盟自带toast提示
		mController_share.openShare((Activity) mContext, false);

		// ---------------------------新增
		WeiXinShareContent WeixinShareContent1 = new WeiXinShareContent();
		WeixinShareContent1.setTitle(redBean.title);
		WeixinShareContent1.setTargetUrl(redBean.url);
		// 设置分享文字内容
		WeixinShareContent1.setShareContent(redBean.describe);
		// 设置分享图片
		WeixinShareContent1.setShareImage(new UMImage(mContext, redBean.coverImg));
		mController_share.setShareMedia(WeixinShareContent1);
		// ---------------------------新增结束

		// 设置微信朋友圈分享内容
		CircleShareContent circleMedia = new CircleShareContent();
		circleMedia.setShareContent(redBean.describe);
		circleMedia.setTitle(redBean.title);
		circleMedia.setShareImage(new UMImage(mContext, redBean.coverImg));
		circleMedia.setTargetUrl(redBean.jumpUrl);
		mController_share.setShareMedia(circleMedia);
		// mController_share.getConfig().setPlatformOrder(SHARE_MEDIA.WEIXIN,
		// SHARE_MEDIA.WEIXIN_CIRCLE);
		// WXEntryActivity.action = "shareToCircle";// 设置与微信平台交互动v作：分享到朋友圈
		// 直接分享
		// mController_share.postShare(mContext, SHARE_MEDIA.WEIXIN_CIRCLE, new
		// SnsPostListener() {
		// @Override
		// public void onStart() {
		// // Toast.makeText(Business.this.contextByActivity,
		// // "开始分享.", Toast.LENGTH_SHORT).show();
		// }
		//
		// @SuppressWarnings("unchecked")
		// @Override
		// public void onComplete(SHARE_MEDIA platform, int eCode,
		// SocializeEntity entity) {
		// if (eCode == 200) {
		// ToastUtil.showShortMsg("分享朋友圈成功!");
		// // 去分享成功的弹窗
		// // Intent intent = new Intent(mContext,
		// // RankingPopWindowsActivity.class);
		// // intent.putExtra("MYACTION",
		// // MyUtil.INTENT_MYACTION_SHARESUCCESS_TO_RANKPOPWIN);
		// // IndexActivity.this.startActivity(intent);
		// if (mDelegate != null) {
		// Map<String, String> params = new TreeMap<String, String>();
		// params.put("activeId", redBean.activeId);
		// params.put("userId", ServiceAuthManager.getUserId(mContext));
		// new RedPackTask(mContext, RedPackTask.TASKID,
		// mDelegate).execute(params);
		// if (KLog.isShow) {
		// ToastUtil.showShortMsg("分享获取红包");
		// }
		// }
		//
		// } else {
		// String eMsg = "";
		// if (eCode == -101) {
		// eMsg = "没有授权";
		// }
		// Toast.makeText(mContext, "分享失败[" + eCode + "] " + eMsg,
		// Toast.LENGTH_SHORT).show();
		// }
		// }
		//
		// });
		// mController_share.postShare(mContext, SHARE_MEDIA.WEIXIN, new
		// SnsPostListener() {
		// @Override
		// public void onStart() {
		// // Toast.makeText(Business.this.contextByActivity,
		// // "开始分享.", Toast.LENGTH_SHORT).show();
		// }
		//
		// @SuppressWarnings("unchecked")
		// @Override
		// public void onComplete(SHARE_MEDIA platform, int eCode,
		// SocializeEntity entity) {
		// if (eCode == 200) {
		// ToastUtil.showShortMsg("分享成功!");
		// } else {
		// String eMsg = "";
		// if (eCode == -101) {
		// eMsg = "没有授权";
		// }
		// Toast.makeText(mContext, "分享失败[" + eCode + "] " + eMsg,
		// Toast.LENGTH_SHORT).show();
		// }
		// }
		//
		// });
	}

	/**
	 * 友盟 直接分享微信朋友圈
	 */
	public void WxShareWxCircleByUm(final ActiviteDetailBean activeBean) {
		if (mContext == null || activeBean == null) {
			return;
		}
		// 添加微信平台
		UMWXHandler wxHandler = new UMWXHandler(mContext, WXAuthByUm.wxAPPID, WXAuthByUm.wxAPPSECRET);
		wxHandler.addToSocialSDK();
		wxHandler.showCompressToast(false);
		// 添加微信朋友圈
		UMWXHandler wxCircleHandler = new UMWXHandler(mContext, WXAuthByUm.wxAPPID, WXAuthByUm.wxAPPSECRET);
		wxCircleHandler.setToCircle(true);
		wxCircleHandler.addToSocialSDK();
		wxCircleHandler.showCompressToast(false);// 去掉微信自身的toast

		UMSocialService mController_share = UMServiceFactory.getUMSocialService("com.umeng.share");// 友盟分享
		mController_share.getConfig().removePlatform(SHARE_MEDIA.SINA, SHARE_MEDIA.QZONE, SHARE_MEDIA.QQ, SHARE_MEDIA.TENCENT);
		mController_share.getConfig().setPlatformOrder(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE);
		mController_share.getConfig().closeToast();// 关掉友盟自带toast提示

		// ---------------------------新增
		// WeiXinShareContent WeixinShareContent1 = new WeiXinShareContent();
		// WeixinShareContent1.setTitle(redBean.title);
		// WeixinShareContent1.setTargetUrl(redBean.url);
		// WeixinShareContent1.setShareContent(redBean.describe);
		// WeixinShareContent1.setShareImage(new UMImage(mContext,
		// redBean.coverImg));
		// mController_share.setShareMedia(WeixinShareContent1);

		// 设置微信朋友圈分享内容
		CircleShareContent circleMedia = new CircleShareContent();
		circleMedia.setShareContent(activeBean.describe);
		circleMedia.setTitle(activeBean.title);
		circleMedia.setShareImage(new UMImage(mContext, activeBean.coverImg));
		circleMedia.setTargetUrl(activeBean.jumpUrl);
		mController_share.setShareMedia(circleMedia);
		// 直接分享
		mController_share.postShare(mContext, SHARE_MEDIA.WEIXIN_CIRCLE, new SnsPostListener() {
			@Override
			public void onStart() {
			}

			@SuppressWarnings("unchecked")
			@Override
			public void onComplete(SHARE_MEDIA platform, int eCode, SocializeEntity entity) {
				if (eCode == 200) {
					// ToastUtil.showShortMsg("分享朋友圈成功!");
					Map<String, String> params = new TreeMap<String, String>();
					params.put("activeId", activeBean.activeId);
					params.put("api_key", ServiceAuthManager.getToken(mContext));
					String userId = ServiceAuthManager.getUserId(mContext);
					if (KStringTool.isEmpty(userId)) {
						userId = "-1";
					}
					params.put("userId", userId);
					new RedPackTask(mContext, RedPackTask.TASKID, new TaskDelegate() {
						@Override
						public void faild_TaskDelegate(int taskId, Object object) {
						}

						@Override
						public void success_TaskDelegate(int taskId, Object object) {
							// 红包获取成功
							LuckyMoneyActivityFragment.sendBroadcast(mContext);
						}
					}).execute(params);
					KLog.e(TAG, "分享获取红包");

				} else {
					String eMsg = "";
					if (eCode == -101) {
						eMsg = "没有授权";
					}
					// Toast.makeText(mContext, "分享失败[" + eCode + "] " + eMsg,
					// Toast.LENGTH_SHORT).show();
				}
			}

		});
	}

	/**
	 * 友盟 直接分享到 微信群
	 */
	public void WxShareByUm(final ActiviteDetailBean activeBean) {
		if (mContext == null || activeBean == null) {
			return;
		}
		// 添加微信平台
		UMWXHandler wxHandler = new UMWXHandler(mContext, WXAuthByUm.wxAPPID, WXAuthByUm.wxAPPSECRET);
		wxHandler.addToSocialSDK();
		wxHandler.showCompressToast(false);
		// 添加微信朋友圈
		UMWXHandler wxCircleHandler = new UMWXHandler(mContext, WXAuthByUm.wxAPPID, WXAuthByUm.wxAPPSECRET);
		wxCircleHandler.setToCircle(true);
		wxCircleHandler.addToSocialSDK();
		wxCircleHandler.showCompressToast(false);// 去掉微信自身的toast

		UMSocialService mController_share = UMServiceFactory.getUMSocialService("com.umeng.share");// 友盟分享
		mController_share.getConfig().removePlatform(SHARE_MEDIA.SINA, SHARE_MEDIA.QZONE, SHARE_MEDIA.QQ, SHARE_MEDIA.TENCENT);
		mController_share.getConfig().setPlatformOrder(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE);
		mController_share.getConfig().closeToast();// 关掉友盟自带toast提示

		WeiXinShareContent WeixinShareContent1 = new WeiXinShareContent();
		WeixinShareContent1.setTitle(activeBean.title);
		WeixinShareContent1.setTargetUrl(activeBean.url);
		WeixinShareContent1.setShareContent(activeBean.describe);
		WeixinShareContent1.setShareImage(new UMImage(mContext, activeBean.coverImg));
		mController_share.setShareMedia(WeixinShareContent1);

		// 设置微信朋友圈分享内容
		// CircleShareContent circleMedia = new CircleShareContent();
		// circleMedia.setShareContent(redBean.describe);
		// circleMedia.setTitle(redBean.title);
		// circleMedia.setShareImage(new UMImage(mContext, redBean.coverImg));
		// circleMedia.setTargetUrl(redBean.jumpUrl);
		// mController_share.setShareMedia(circleMedia);
		// WXEntryActivity.action = "shareToCircle";// 设置与微信平台交互动v作：分享到朋友圈
		// 直接分享
		mController_share.postShare(mContext, SHARE_MEDIA.WEIXIN, new SnsPostListener() {
			@Override
			public void onStart() {
			}

			@Override
			public void onComplete(SHARE_MEDIA platform, int eCode, SocializeEntity entity) {
				if (eCode == 200) {
					// ToastUtil.showShortMsg("分享成功!");
				} else {
					String eMsg = "";
					if (eCode == -101) {
						eMsg = "没有授权";
					}
					// ToastUtil.showShortMsg("分享失败[" + eCode + "] " + eMsg);
				}
			}

		});
	}

	private LoadingProgressDialog progressDialog;

	protected void startProgressDialog() {
		if (progressDialog == null) {
			progressDialog = LoadingProgressDialog.createDialog(mContext);
			progressDialog.setMessage("请稍候...");
			progressDialog.setCancelable(true);
		}
		progressDialog.show();
	}

	protected void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}
}
